package com.iwhalecloud.bss.kite.cucc.service.scene;

import com.iwhalecloud.bss.kite.cart.service.shoppingcart.loader.impl.KiteCartSceneInstLoader;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.manager.dto.KiteSceneInstDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.scene.service.QuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.scene.service.operate.CreateSceneInstService;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.manager.transaction.TransactionContext;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyx
 * @version V1.0
 * @Description:
 * @date 2021/7/28
 * @Package com.iwhalecloud.bss.kite.cucc.service.scene
 */
@Primary
@Service
public class CuccQuerySceneInstService extends QuerySceneInstService {

    @Resource(name = "manager.createSceneInstService")
    private CreateSceneInstService createSceneInstService;

    @Override
    public KiteSceneInst getSceneInst(String sceneInstId, String custId) {
        KiteSceneInst sceneInst = null;
        try {
            sceneInst = TransactionContext.getContainer().getSceneInst(sceneInstId);
        }
        catch (BssException e) {
            if (!Objects.equals(ErrorConsts.SCENE_INST_NOT_EXISTS.getCode(), e.getFailCode())) {
                throw e;
            }
        }

        if (Objects.isNull(sceneInst)) {
            KiteCartSceneInstLoader sceneInstLoader = SpringUtil.getBean(KiteCartSceneInstLoader.class);
            KiteSceneInstDTO sceneInstDTO = sceneInstLoader.loadInst(custId, sceneInstId);
            sceneInst = createSceneInstService.restoreSceneInst(sceneInstDTO);
        }

        if (Objects.isNull(sceneInst)) {
            ErrorConsts.SCENE_INST_NOT_EXISTS.throwOut(sceneInstId);
        }

        return sceneInst;
    }
}
